import router, { asyncRoutes, constantRoutes } from '../../router/index'

const state = () => ({
  allRoutes: constantRoutes
})

const mutations = {
  setRoutes(state, newRoutes) {
    state.allRoutes = newRoutes
  }
}

const actions = {
  filterRoutes(context) {
    const _menus = context.rootState.user.userInfo.roles.menus
    const _newRoutes = asyncRoutes.filter(v => {
      const _len = v.children.filter(child => {
        return _menus.includes(child.name)
      }).length
      if (_len > 0) {
        return true
      } else {
        return false
      }
    })
    _newRoutes.push({ path: '*', redirect: '/404', hidden: true })
    router.addRoutes(_newRoutes)
    context.commit('setRoutes', [...constantRoutes, ..._newRoutes])
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
